import 'dart:convert';
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../../bean/userinfo_bean.dart';
import '../../common/system_config.dart';
import '../../model/initapp_model.dart';
import '../../model/theme_model.dart';
import '../../utils/tools/localstorage_tool.dart';
import '../../utils/tools/screenutil_tool.dart';
import '../../utils/widget/appbar_widget.dart';
import '../../utils/widget/dialog_widget.dart';
import '../../utils/widget/fixedtip_widget.dart';
import '../../viewmodel/base_vm.dart';
import '../../viewmodel/userinfo_vm.dart';
import 'components/rowtext_widget.dart';

class PersonalCenterView extends StatefulWidget {
  @override
  PersonalCenterViewState createState() => new PersonalCenterViewState();
}

class PersonalCenterViewState extends State<PersonalCenterView> {
  // 用户信息
  UserInfoBean userinfo;

  // 主题信息
  bool themeInfo = false;

  // 网络状态
  bool networkstate;

  // * 统计各项函数被执行的次数
  int implementCount = 0;

  // 标记当前app的状态（特指：异常情况0：网络异常  1：WebSocket已断开   2：重连WebSocket）
  int componentState;

  // 平台条件（android：true/ios：false）
  bool platformInfo = Platform.isAndroid;

  // 缓存中用户的数据
  String _userInfo_str;

  @override
  Widget build(BuildContext context) {
    // 列表项行高
    double line_HD = ST.seth(100);

    // 列表项字体大小
    TextStyle textStyle = TextStyle(fontSize: SystemConfig.fs_content3);

    return Scaffold(
      appBar: AppBarWidget("个人中心").build(context),
      body: Consumer<InitAppModel>(
        builder: (context, model, child) {
          // 将网络状态存储为全局状态，便于其他函数访问。（该状态会实时更新）
          networkstate = model.networkstate;

          // 必须保证网络通畅
          if (networkstate) {
            // 标记网络已恢复
            componentState = null;

            // 检查是否为初始化状态
            if (implementCount <= 0) {
              // 发起网络请求，获取页面数据
              initPage(context);

              // 统计执行次数
              implementCount++;
            }
          } else {
            // 标记网络异常
            componentState = 0;

            // 还原组件初始化状态
            if (implementCount > 0) {
              implementCount = 0;
            }
          }

          // 绘制组件
          return Stack(
            children: [
              SingleChildScrollView(
                child: Container(
                  padding: EdgeInsets.only(
                      top: model.networkstate ? 0 : ST.seth(76)),
                  color: Theme.of(context).backgroundColor,
                  child: Column(
                    children: [
                      Container(
                        width: double.infinity,
                        padding: EdgeInsets.symmetric(
                            horizontal: ST.setw(32), vertical: ST.seth(30)),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Container(
                              width: ST.setw(160),
                              child: ClipRRect(
                                borderRadius: BorderRadius.circular(80),
                                child: Image(
                                  image:
                                      AssetImage('assets/images/userHead.jpg'),
                                  fit: BoxFit.cover,
                                ),
                              ),
                            ),
                            SizedBox(height: ST.seth(10)),
                            Container(
                              child: RowTextWidget(userinfo),
                            )
                          ],
                        ),
                      ),
                      Divider(
                        height: ST.seth(1),
                        color: SystemConfig.borderColor,
                        indent: 0,
                      ),
                      platformInfo
                          ? SizedBox.shrink()
                          : Container(
                              height: line_HD,
                              padding:
                                  EdgeInsets.symmetric(horizontal: ST.setw(32)),
                              child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  Text("${themeInfo ? "关闭" : "开启"}深夜模式",
                                      style: textStyle),
                                  Switch(
                                    value: themeInfo,
                                    activeColor: SystemConfig.themeColor,
                                    onChanged: (value) {
                                      //LocalStorage.remove("userdata");
                                      Provider.of<ThemeModel>(context,
                                              listen: false)
                                          .reverse();
                                      setState(() {
                                        themeInfo = value;
                                      });
                                    },
                                  ),
                                ],
                              ),
                            ),
                      platformInfo
                          ? SizedBox.shrink()
                          : Divider(
                              height: ST.seth(1),
                              color: SystemConfig.borderColor,
                              indent: ST.setw(32),
                            ),
                      Container(
                        height: line_HD,
                        padding: EdgeInsets.symmetric(horizontal: ST.setw(32)),
                        child: InkWell(
                          onTap: () =>
                              Navigator.pushNamed(context, '/changepwdview'),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text("修改密码", style: textStyle),
                              Icon(Icons.keyboard_arrow_right,
                                  size: ST.setsp(48),
                                  color: SystemConfig.grayColor)
                            ],
                          ),
                        ),
                      ),
                      Divider(
                        height: ST.seth(1),
                        color: SystemConfig.borderColor,
                        indent: ST.setw(32),
                      ),
                      Container(
                        height: line_HD,
                        padding: EdgeInsets.symmetric(horizontal: ST.setw(32)),
                        child: InkWell(
                          onTap: () =>
                              Navigator.pushNamed(context, "/introduceview"),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text("关于App", style: textStyle),
                              Icon(Icons.keyboard_arrow_right,
                                  size: ST.setsp(48),
                                  color: SystemConfig.grayColor)
                            ],
                          ),
                        ),
                      ),
                      Divider(
                        height: ST.seth(1),
                        color: SystemConfig.borderColor,
                        indent: ST.setw(32),
                      ),
                      Container(
                        height: line_HD,
                        padding: EdgeInsets.symmetric(horizontal: ST.setw(32)),
                        child: InkWell(
                          onTap: () => Dialogs.confirmDialog(context,
                              content: "退出将需要重新登录，您是否继续？",
                              confirmCallback: () async {
                            var result =
                                await BaseVM.exitSystem(context, "正在退出");
                            if (result["code"] == 1) {
                              Navigator.pushNamedAndRemoveUntil(
                                  context, "/loginview", (_) => false);
                            }
                          }),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text("退出登录", style: textStyle),
                              Icon(Icons.keyboard_arrow_right,
                                  size: ST.setsp(48),
                                  color: SystemConfig.grayColor)
                            ],
                          ),
                        ),
                      ),
                      Divider(
                        height: ST.seth(1),
                        color: SystemConfig.borderColor,
                        indent: 0,
                      )
                    ],
                  ),
                ),
              ),
              componentState == null
                  ? SizedBox.shrink()
                  : Positioned(
                      top: 0,
                      left: 0,
                      right: 0,
                      child: FixedTopWidget(componentState),
                    ),
            ],
          );
        },
      ),
    );
  }

  /// 初始化页面
  /// * [context] 必填|上下文
  void initPage(BuildContext context) async {
    if (UserInfoBean.id == null) {
      UserInfoBean result;
      result = await UserInfoVM().initUserInfo(context, title: "正在获取...");
      // 更新界面
      setState(() {
        userinfo = result;
      });
//      print("123");
    } else {
      userinfo = UserInfoBean.getInstance().getUserInfoBean();
//      print(456);
    }

    // 存储缓存
//    LocalStorage.setFormat("userInfo", result);

    // 获取缓存中的用户数据
//    String _userInfo_str = await LocalStorage.getFormat("userInfo");
//    print(_userInfo_str);
//
//    if (_userInfo_str != null) {
//      // 更新界面
//      setState(() {
//        userinfo = UserInfoBean.fromJson(json.decode(_userInfo_str));
//      });
//    } else {
//      // 获取用户信息
//      UserInfoBean result =
//          await UserInfoVM().initUserInfo(context, title: "正在获取...");
//
//      // 存储缓存
//      LocalStorage.setFormat("userInfo", result);
//
//      // 更新界面
//      setState(() {
//        userinfo = result;
//      });
//    }
  }

  /// 获取当前主题
  void initThemeType() async {
    String lsThemeType = await LocalStorage.getStringItem("themeContext");
    bool b;

    if (lsThemeType == "ThemeType.dark")
      b = true; //暗调
    else
      b = false; //高亮

    // 设置主题
    setState(() {
      themeInfo = b;
    });
  }

  @override
  void initState() {
    super.initState();

    // 执行初始化主题
    initThemeType();
  }
}
